package demo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import me.prettyprint.cassandra.model.CqlQuery;
import me.prettyprint.cassandra.model.CqlRows;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.template.ColumnFamilyTemplate;
import me.prettyprint.cassandra.service.template.ColumnFamilyUpdater;
import me.prettyprint.hector.api.beans.Row;
import me.prettyprint.hector.api.exceptions.HectorException;
import me.prettyprint.hector.api.query.QueryResult;

public class CompanyBO {
	
	public void addCompany(String key, String companyName, String companyAddress) {
		// Insert data into Company table
		ColumnFamilyTemplate<String, String> companyTemplate = (ColumnFamilyTemplate<String, String>) Template.getTemplate("Company");
		ColumnFamilyUpdater<String, String> companyUpdater = companyTemplate.createUpdater(key);
		companyUpdater.setString("Company_name", companyName);
		companyUpdater.setString("Address", companyAddress);
		
		try {
			companyTemplate.update(companyUpdater);
		} catch (HectorException ex) {
			ex.printStackTrace();
		}
	}
	
	public List<Company> retrieveCompanies() {
		CqlQuery<String, String, String> cql = new CqlQuery<String, String, String>(Template.getKeyspace(), 
				StringSerializer.get(), 
				StringSerializer.get(), 
				StringSerializer.get());
		
		cql.setQuery("SELECT * FROM Company");
		QueryResult<CqlRows<String, String, String>> result = cql.execute();
		Iterator<Row<String, String, String>> rows = result.get().iterator();
		Row<String, String, String> row = null;
		List<Company> companies = new ArrayList<Company>();
		while (rows.hasNext()) {
			row = rows.next();
			String companyName = row.getColumnSlice().getColumnByName("Company_name").getValue();
			String companyAddress = row.getColumnSlice().getColumnByName("Address").getValue();
			companies.add(new Company(row.getKey(), companyName, companyAddress));
		}
		
		return companies;
	}
}
